package juc.day1;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Description: 多线程
 *
 * @Autor: Rolin
 * datetime: 09-10-17:23
 */
@Slf4j
public class Async {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
        test2();
        System.out.println((Integer) test3());

        //线程切换条件测试
        testOrder();

        test4();

    }

    private static void test4() {
        Thread t = new Thread("Thread1"){
            @Override
            public void run() {
                log.debug("sleeping...");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    log.debug("waking up...");
                    e.printStackTrace();
                }
            }
        };
        t.start();

        try {
            log.debug("interrupt...");
            Thread.sleep(1000);
            t.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void testOrder() {
        Thread t3 = new Thread(() -> {
            System.out.println("thread3");
        });

        Thread t = new Thread(() -> {
            System.out.println("thread1");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            System.out.println("thread2");
        });

        t3.start();
        t.start();
        t2.start();
        log.debug("{}",t.getState());



    }

    private static <T> T test3() throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(1000);
                return 100;
            }
        });
        Thread test3 = new Thread(futureTask, "test3");
        test3.start();
        return (T) futureTask.get();
    }


    private static void test2() {
        Thread t = new Thread("test2") {
            @Override
            public void run() {
                log.debug("concurrent2");
            }
        };
        t.start();
    }

    private static void test1() {
        Runnable r = () -> log.debug("concurrent1");
        Thread thread = new Thread(r);
        thread.start();
    }
}
